package np.com.abhishek.sudoku.ui;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

class Cell extends JTextField implements KeyListener, FocusListener {
    int cellValue;

    private static final long serialVersionUID = 1L;

    Cell() {
	// is called to create the cells initially
	super();
	cellValue = 0;
	addKeyListener(this);
	addFocusListener(this);
	setFont(new Font("Times New Roman", Font.BOLD, 25));
	setForeground(Color.red);
	setHorizontalAlignment(SwingConstants.CENTER);

    }

    int getValue() {
	int a = 0;
	/*
	 * the function getText() return 0 even if the fields of the textbox are
	 * empty hence there is no way of knowing whether the user has left the
	 * field blank or supplied 0 so here I'm making the function to return
	 * -1 if the user has intentionally supplied 0 to distinguish the case
	 */
	if (getText().equals("0"))
	    a = -1;
	else {
	    try {
		a = Integer.parseInt(getText());
	    } catch (Exception e) {
	    }
	}
	return a;
    }

    void putValue(int cellValue) {
	this.cellValue = cellValue;
	setFont(new Font("Times New Roman", Font.BOLD, 25));
	setForeground(Color.black);
	setText("" + cellValue);
    }

    void emptyCell() {
	// is invoked when the cell needs to be emptied ie in case of invalid
	// key(s) pressed by user
	setText("");
	cellValue = 0;
    }

    public void keyTyped(KeyEvent ke) {
    }

    public void keyPressed(KeyEvent ke) {
    }

    public void keyReleased(KeyEvent ke) {
	/*
	 * since only numbers are allowed from 1 to 9 ASCII(0) = 48.... ASCII(9) =
	 * 57 ASCII(0) = 48 or 96 thus we should not consider them as we need
	 * only between 1-9 but if 0 is not accepted then users are not allowed
	 * type 10 20 & so on but can type 11 12 or so on, thus to become
	 * consistent I'm considering for 0 49 to 57 are for the normal number
	 * keys (above the the alphabets) 97 to 105 are for the Numlocked keys
	 * (they are numbers too... can't ignore 'em....
	 */
	if ((ke.getKeyCode() < 48 || ke.getKeyCode() > 57)
		&& (ke.getKeyCode() < 96 || ke.getKeyCode() > 105)) {
	    /*
	     * keys other than number keys are pressed! so empty the cell
	     */
	    emptyCell();
	}
    }

    public void focusGained(FocusEvent fe) {
    }

    public void focusLost(FocusEvent fe) {
	if (!fe.isTemporary()) {
	    // System.out.println("adf:" + getValue());
	    if (getValue() != 0) {
		if (getValue() > 9 || getValue() < 1) {
		    JOptionPane.showMessageDialog(null,
			    "Please enter numbers between 1-9.",
			    "Invalid Number", JOptionPane.INFORMATION_MESSAGE);
		    emptyCell();
		    requestFocus();
		}
	    }
	}
    }
}